.globl dot

.text
# =======================================================
# FUNCTION: Dot product of 2 int arrays
# Arguments:
#   a0 (int*) is the pointer to the start of arr0
#   a1 (int*) is the pointer to the start of arr1
#   a2 (int)  is the number of elements to use
#   a3 (int)  is the stride of arr0
#   a4 (int)  is the stride of arr1
# Returns:
#   a0 (int)  is the dot product of arr0 and arr1
# Exceptions:
#   - If the length of the array is less than 1,
#     this function terminates the program with error code 36
#   - If the stride of either array is less than 1,
#     this function terminates the program with error code 37
# =======================================================
dot:
	# Prologue
    ble a2, x0, error_length
    ble a3, x0, error_stride
    ble a4, x0, error_stride
    lw t1, 0(a0)   # element of arr0
    lw t2, 0(a1)   # element of arr1
    addi sp, sp, -4
    sw s1, 0(sp)   # save s1
    add s1, x0, x0 # s1 = 0
    slli a3, a3, 2
    slli a4, a4, 2
    add t3, a0, x0 # address arr0
    add a0, x0, x0 # result
loop_start:
    mul t4, t1, t2
    add a0, a0, t4
    addi s1, s1, 1  # a2 should be an array's element to use.
    beq s1, a2, loop_end
    add t3, t3, a3
    add a1, a1, a4
    lw t1, 0(t3)
    lw t2, 0(a1)
    j loop_start
error_length:
    li a0, 36
    j exit
error_stride:
    li a0, 37
    j exit
loop_end:
	# Epilogue
    lw s1, 0(sp)
    addi sp, sp, 4
	ret